local sort_list = require"module.render.sort_list"

local zlist = class("ZList"){
    segments = nil;
    segments_table = {},
    segment_size = 200;
    objects = {}
}

function zlist:__init__(segment_size)
    self.segment_size = segment_size or 200
    self.segments = sort_list()
end

function zlist:clear()
    self.segments = sort_list()
    self.segments_table = {}
    self.objects = {}
end

function zlist:get_segment(z_index)
    local segment_index = math.floor(z_index / self.segment_size)
    if self.segments_table[segment_index] == nil then
        local segment =  sort_list()
        self.segments_table[segment_index] = segment
        self.segments:add(segment_index,segment)
    end
    return self.segments_table[segment_index]
end

function zlist:add(z_index,entity)
    local segment = self:get_segment(z_index)
    if segment:add(z_index,entity) then
        self.objects[entity] = entity
    end
end

function zlist:remove(z_index,entity)
    local segment = self:get_segment(z_index)
    if segment:remove(entity) then
        self.objects[entity] = nil
    end
end

function zlist:update_z_index(entity,old_z_index,new_z_index)
    local old_seg = self:get_segment(old_z_index)
    local new_seg = self:get_segment(new_z_index)
    old_seg:remove(entity)
    new_seg:add(new_z_index,entity)
end

function zlist:foreach(func)
    for segment in self.segments:items() do
        for entity in segment.data:items() do
            func(entity.data)
        end
    end
end

return zlist